#coding:utf-8
__author__ = 'dong'

import urllib
import urllib2
import cookielib
import Image
from lxml import etree
import re
import downVideo

class DownCourse(object):
    def __init__(self):
        # 初始化一个CookieJar来处理Cookie
        cookieJar = cookielib.CookieJar()
        # 实例化一个全局opener
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
        # cookie处理机制装上
        urllib2.install_opener(opener)

    # login
    def login(self):
        # 从登录页面获取登陆参数
        login_url = 'http://passport.jikexueyuan.com/sso/login'
        # 获取验证码
        verifyCode_url = 'http://passport.jikexueyuan.com/sso/verify'
        # 登陆信息发送到这个地址
        passport_url = 'http://passport.jikexueyuan.com/submit/login?is_ajax=1'

        # 获取登陆信息expire
        request = urllib2.urlopen(login_url).read()
        selector = etree.HTML(request)
        expire = selector.xpath('//*[@id="login-form"]/input/@value')

        # 获取验证码
        verifyCodeGifPath = 'verify.gif'
        request = urllib2.urlopen(verifyCode_url)
        gif = request.read()
        request.close()
        with open(verifyCodeGifPath, 'wb') as fGif:
            fGif.write(gif)
        # 读取保存到本地的验证码图片
        # os.system('eog ' + verifyCodeGifPath)
        verifyImage = Image.open(verifyCodeGifPath)
        verifyImage.show()
        verifyText = raw_input(u"请输入图中的验证码:")

        # 要提交的数据列表
        data = {
            'expire':expire[0],
            'uname':'dong1248',
            'password':'1248163264',
            'verify':verifyText,
        }

        post_data = urllib.urlencode(data)

        request = urllib2.Request(passport_url, post_data)
        # 添加数据头
        request.add_header('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36')
        # 发送登陆请求
        request = urllib2.urlopen(request)
        print request.read().decode('utf-8')
        request.close()

    def downLoad(self, courseUrl):
        urlContent = urllib2.urlopen(courseUrl).read()
        selector = etree.HTML(urlContent)
        # 获取课程名称
        courseName = selector.xpath('/html/head/title/text()')
        # print courseName[0]
        # 获取课程数量
        courseCount = int(re.search(r'(?s)class="timebox"><span>(.*?)课时',urlContent).group(1))
        # print courseCount

        fileNameList = []
        urlList = []
        i = 0
        while i < courseCount:
            i += 1
            # 构造课程页面地址
            pageUrl = courseUrl.split('.html')[0] + '_' + str(i) + '.html?ss=1'
            request = urllib2.urlopen(pageUrl)
            pageHtml = request.read()
            request.close()
            selector = etree.HTML(pageHtml)
            courseName = selector.xpath('/html/head/title/text()')
            # fileName = courseName[0].split('-')[0]
            fileName = courseName[0].split('-')[0]
            fileNameList.append(fileName)
            videoUrl = re.search(r'<source src="(.*?)"',pageHtml)
            if videoUrl == None:
                continue
            else:
                # print videoUrl.group(1)
                videoUrl = videoUrl.group(1)
                urlList.append(videoUrl)

        downFile(fileNameList, urlList)

def downFile(fileName, url):
    # 发送前，把原来的字典清空
    fileName_Url = {}
    # 把list生成dict
    for (k, v) in zip(fileName, url):
            fileName_Url[k] = v

    downVideo.main(fileName_Url)


if __name__ == '__main__':
    jike = DownCourse()
    jike.login()
    # Flask应用部署与运维 http://www.jikexueyuan.com/course/2060.html
    # Python 标准库与其他应用 http://www.jikexueyuan.com/course/2003.html
    # jike.downLoad('http://www.jikexueyuan.com/course/2003.html')
    urlList = [
        'http://www.jikexueyuan.com/course/201.html',
        'http://www.jikexueyuan.com/course/503.html',
        'http://www.jikexueyuan.com/course/203.html',
        'http://www.jikexueyuan.com/course/202.html',
        'http://www.jikexueyuan.com/course/548.html',
        'http://www.jikexueyuan.com/course/594.html',
        'http://www.jikexueyuan.com/course/623.html',
        'http://www.jikexueyuan.com/course/679.html',
        'http://www.jikexueyuan.com/course/695.html',
        'http://www.jikexueyuan.com/course/699.html',
    ]
    for each in urlList:
        jike.downLoad(each)